package com.topisv.tms.platform.jd;

import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.utils.http.HttpPost;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/jd")
public class JdController {
	
	private static final Logger logger = LoggerFactory.getLogger(JdController.class);
	

	@Autowired
	private ShopSourceService shopSourceService;
	static String appSecret=null;
	static String appKey=null;
	static String url=null;
	
	@RequestMapping(value = "init")
	public void init(@RequestParam(value = "code") String code,
			@RequestParam(value = "state") String state, HttpServletResponse response) {
		String url ="http://auth.sandbox.360buy.com/oauth/token?grant_type=authorization_code&client_id="+appKey
        +"&client_secret="+ appSecret +"&redirect_uri="+ JdController.url +"&code="+ code+"&state=1234";
		JSONObject json=null;
		PrintWriter out=null;
	    try {
	    	out=response.getWriter();
			String result=HttpPost.pub(url);
			logger.info("返回的结果为:"+result);
			json=new JSONObject();
			json=JSONObject.fromObject(result);
			String accessToken=(String)json.get("access_token");
			ShopSource shopSource=shopSourceService.findByJdKeyAndJdSecret(appKey, appSecret);
			shopSource.setJdAccessToken(accessToken);
			shopSource.setJdTokenDate(new Date());
			shopSourceService.save(shopSource);
			out.print(result);
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			logger.error("error",e);
		}
	}
	
	@RequestMapping(value = "ajaxGetJdMessage")
	public void ajaxGetJdMessage(@RequestParam(value = "shopCode") String shopCode,HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			out=response.getWriter();
			json=new JSONObject();
			ShopSource shopSource=shopSourceService.findByShopCode(shopCode);
			if(shopSource==null){
				json.put("status", "-1");
				json.put("content", "该数据源平台不存在");
				out.print(json.toString());
				return;
			}
			JdController.appSecret=shopSource.getJdSecret();
			JdController.appKey=shopSource.getJdKey();
			JdController.url=shopSource.getJdBackServerUrl();
			json.put("status", "1");
			json.put("appKey", JdController.appKey);
			json.put("backServerUrl", JdController.url);
			json.put("appSecret", JdController.appSecret);
			out.print(json.toString());
			logger.info(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
	}
}
